package com.vanke.agent;

//
// Copyright (c) 2014, 保留所有权利。
//
// Config.java
//
// 作    者：王红燕
// 当前版本：1.0
//

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
public class Config {
	static final Map<String, String> values = new ConcurrentHashMap<String, String>();
	static {
		load();
	}

	public static void load() {
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "select paramsname,paramsvalue from crm_tsys_params";
		try {
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String name = rs.getString(1);
				String value = rs.getString(2);
				if (name == null || value == null) {
					continue;
				}
				values.put(name.trim(), value.trim());
			} // end while
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(rs, stmt, con);
		}
	} //~load()

	public static String get(String key) {
		String val = values.get(key);
		return val == null ? "" : val;
	}

	public static void set(String key, String value) {
		if (key == null) {
			return;
		}
		values.put(key, value);
	}

	public static void save() {
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);
		PreparedStatement pstmt = null;
		String sql = "update crm_tsys_params set paramsvalue=? where paramsname=?";
		try {
			pstmt = con.prepareStatement(sql);
			Iterator<Entry<String, String>> iter = values.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, String> entry = iter.next();
				pstmt.setString(1, entry.getValue()); 	// paramsvalue
				pstmt.setString(2, entry.getKey());		// paramsname
				pstmt.addBatch();
			} // end while
			pstmt.executeBatch();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(null, pstmt, con);
		}
	} //~save

	public static void main(String[] args) throws Exception {
		// Map<String, String> values
		Iterator<Entry<String, String>> iter = values.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			System.out.println(entry.getKey() + " : " + entry.getValue());
		}
	}
}
